package com.example.administrator.szb.activity.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.WecomeActivity;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.bean.JClientBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.util.FinishActivity;
import com.example.administrator.szb.util.IosDiaolog;
import com.example.administrator.szb.util.JPushUtils;
import com.example.administrator.szb.util.LogoutDialog;
import com.example.administrator.szb.util.Permission;
import com.example.administrator.szb.util.StatusBarUtil;
import com.example.zhouwei.library.CustomPopWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by Administrator on 2017/9/5.
 */

public class BaseActivity extends AppCompatActivity implements View.OnTouchListener,Permission.IRoot{
    public View toolbar;
    public CustomPopWindow popWindow;//弹出框
    public PopupWindow popupWindow_wrap;//用于搜索金融机构
    Context context;
    protected IosDiaolog iosDiaolog;
    protected Activity activity;

    public interface Callback {
        void doSomeThing();
    }

    public interface CallbackPopuwindow {
        void doSomeThing(View view);
    }

    private EditText tmpEdit;
    private int tmpEditId;
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
        if ((view.getId() ==tmpEditId && canVerticalScroll(tmpEdit))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
    }
    public void setEditEvent(EditText mtmpEdit,int mtmpEditId){
        tmpEditId=mtmpEditId;
        tmpEdit=mtmpEdit;
        tmpEdit.setOnTouchListener(this);
    }
    /**
     * EditText竖直方向是否可以滚动
     * @param editText  需要判断的EditText
     * @return  true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    /**
     * 权限申请结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            haveRoot(requestCode);
        } else {
            onRequestPermissionsFail(requestCode);
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 拥有权限就执行
     *
     * @param requestCode
     */
    @Override
    public void haveRoot(int requestCode) {
        onRequestPermissionsSuccess(requestCode);
    }

    /**
     * 同上，
     *
     * @param requestCode 请求码
     */
    protected void onRequestPermissionsSuccess(int requestCode) {

    }

    protected void onRequestPermissionsFail(int requestCode) {
        Permission.showMissingPermissionDialog(context);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (SampleApplicationLike.FLAGS == -1) {//flag为-1说明程序被杀掉
            restartApp();
        }else {
            context = this;
            activity=this;
            iosDiaolog = new IosDiaolog(this);
            FinishActivity.add(this);
            EventBus.getDefault().register(this);
            //ChangeStatuUtil.setTranslucentStatus(this);
            //setBarColor();
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            JPushUtils.setALias(this,null);
        }

    }

    public void restartApp() {
        FinishActivity.finish();
        Intent intent = new Intent(this, WecomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
    }
    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        setBarColor();
    }
    /**
     * 设置标题栏颜色
     */
    protected void setBarColor(){
        StatusBarUtil.setColor(this, R.color.basecolor,0);
    }

    /**
     * 初始化toolbar
     *
     * @param
     */
    public void initToolbar(int layout_toolbar, String title) {
        toolbar = findViewById(layout_toolbar);
        ((TextView) toolbar.findViewById(R.id.toolbar_title)).setText(title);
        toolbar.findViewById(R.id.toolbar_fh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 初始化toolbar
     *
     * @param
     */
    public void initToolbar(int layout_toolbar, String title, final Callback callback) {
        toolbar = findViewById(layout_toolbar);
        ((TextView) toolbar.findViewById(R.id.toolbar_title)).setText(title);
        toolbar.findViewById(R.id.toolbar_fh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callback.doSomeThing();
            }
        });
    }


    public void initToolbarThreeImage(int layout_toolbar, String title, int subtitle, final Callback callback) {
        toolbar = findViewById(layout_toolbar);
        ((TextView) toolbar.findViewById(R.id.toolbar_three_text_title)).setText(title);
        toolbar.findViewById(R.id.toolbar_three_image_bsfh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ((ImageView) toolbar.findViewById(R.id.toolbar_three_image_share)).setImageResource(subtitle);
        ((ImageView) toolbar.findViewById(R.id.toolbar_three_image_share)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callback.doSomeThing();
            }
        });
    }


    /**
     * 初始化toolbar
     *
     * @param
     */
    public void initToolbarThree(int layout_toolbar, String title, String subtitle, final Callback callback) {
        toolbar = findViewById(layout_toolbar);
        ((TextView) toolbar.findViewById(R.id.toolbar_three_text_title)).setText(title);
        toolbar.findViewById(R.id.toolbar_three_image_bsfh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ((TextView) toolbar.findViewById(R.id.toolbar_three_text_subtitle)).setText(subtitle);
        ((TextView) toolbar.findViewById(R.id.toolbar_three_text_subtitle)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callback.doSomeThing();
            }
        });
    }

    /**
     * 监听字数变化
     *
     * @param ywxqNoEditXgms
     * @param ywxqNoTextZs
     */
    public void editListenter(EditText ywxqNoEditXgms, final TextView ywxqNoTextZs) {
        ywxqNoEditXgms.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ywxqNoTextZs.setText(charSequence.length() + "/150");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void showPopupwindow(int view_layout_id, View rootview, BaseAdapter adapter) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        //处理popWindow 显示内容
        handleListView(popwindow_view, adapter);
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAsDropDown(rootview);
            // .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
        //显示PopupWindow

    }


    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void showPopupwindow(int view_layout_id, int rootview_layout_id, BaseAdapter adapter) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);
        //处理popWindow 显示内容
        handleListView(popwindow_view, adapter);
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                    .setBgDarkAlpha(0.7f) // 控制亮度
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
        //显示PopupWindow

    }

    /**
     * 处理弹出的popuwindwo 业务
     *
     * @param contentView
     */
    public void handleListView(View contentView, BaseAdapter adapter_choose) {
        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.view_popuwindow_recycler_base_tjzl);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter_choose);
    }


    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void showPopupwindow(int view_layout_id, int width, int height, int rootview_layout_id, CallbackPopuwindow callback) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);
        //处理popWindow 显示内容
        callback.doSomeThing(popwindow_view);
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                    .setBgDarkAlpha(0.7f) // 控制亮度
                    .size(width, height) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAtLocation(rootview, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
        //显示PopupWindow

    }

    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void showPopupwindow_wrap(int margin, int view_layout_id, int rootview_layout_id, CallbackPopuwindow callback) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);
        //处理popWindow 显示内容
        callback.doSomeThing(popwindow_view);
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(false) //弹出popWindow时，背景是否变暗
                    //.setBgDarkAlpha(0.7f) // 控制亮度
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAtLocation(rootview, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, margin);
        }
        //显示PopupWindow
    }

    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void showPopupwindow(int view_layout_id, int width, int height, View rootview_layout_id, CallbackPopuwindow callback) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        View rootview = rootview_layout_id;
        //处理popWindow 显示内容
        callback.doSomeThing(popwindow_view);
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                    .setBgDarkAlpha(0.7f) // 控制亮度
                    .size(width, height) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAsDropDown(rootview);
        }
        //显示PopupWindow

    }


    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    public boolean isRegisterEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100) //在ui线程执行 优先级100
    public void onDataSynEvent(JClientBean event) {
        LogoutDialog.showDialog(context,event.getMsg());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(Util.isOnMainThread()&&!this.isFinishing())
        {
            try {
                Glide.with(this).pauseRequests();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        EventBus.getDefault().unregister(this);
        iosDiaolog.hide();
        HttpUtils.cancleTag(this);
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(iosDiaolog!=null&&iosDiaolog.getPopupWindow().isShowing()&&!iosDiaolog.isAtuoHide()){
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }
}